# 基本异常
try:
    f = open('1.txt', 'r')
    print(f.read())
    f.close()
except:
    print('文件不存在')
finally:
    print('操作结束')

# 捕获指定异常
try:
    f = open('1.txt', 'r')
    print(f.read())
    f.close()
except FileNotFoundError:
    print('文件不存在')
finally:
    print('操作结束')

# 捕获多个指定异常
try:
    f = open('1.txt', 'r')
    print(f.read())
    f.close()
except (FileNotFoundError, NameError):
    print('文件不存在')
finally:
    print('操作结束')

# 捕获所有异常
# Exception是程序异常的父类
try:
    f = open('1.txt', 'r')
    print(f.read())
    f.close()
except Exception as result:
    print(result)
finally:
    print('操作结束')


# 捕获异常描述信息
try:
    f = open('1.txt', 'r')
    print(f.read())
    f.close()
except (FileNotFoundError, NameError) as result:
    print(result)
finally:
    print('操作结束')

# 没有异常时执行
try:
    f = open('test.txt', 'r')
    print(f.read())
    f.close()
except (FileNotFoundError, NameError) as result:
    print(result)
else:
    print('没有错误')

# 自定义异常（继承Exception）
class MyException(Exception):
    def __init__(self, length, min_len):
        self.length = length
        self.min_len = min_len
    # 设置抛出异常的描述信息
    def __str__(self):
        return f'你输入的长度是{self.length},不能少于{self.min_len}'

def main():
    try:
        val = input('请输入：')
        if len(val) < 6:
            # 抛出自定义异常
            raise MyException(len(val), 6)
    except Exception as result:
        print(result)
    else:
        print('输入正确')


main()

